//
//  MatchSave.m
//  cutter
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 e360. All rights reserved.
//

#import "MatchSave.h"
#import "UserCenterPick.h"

//搭配发布
@implementation MatchPublishSuccess
-(void)viewDidLoad{
    [super viewDidLoad];
    [self.nameView setText:[NSString stringWithFormat:@"“%@”已成功发布！", self.name]];
}
-(IBAction)closeTouch:(id)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
@end

//条件筛选
@implementation MatchSaveOptionsCell
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
    [self.selectedView setHidden:!selected];
}
@end
@implementation MatchSaveOptions
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    for (uint i=0; i<[self.data count]; i++) {
        id item = [self.data objectAtIndex:i];
        for (uint j=0; j<[self.classs count]; j++) {
            id temp = [self.classs objectAtIndex:j];
            if ([temp isEqual:item]) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
                break;
            }
        }
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    id item = [self.data objectAtIndex:indexPath.row];
    if (self.type == 2) {
        MatchSaveOptionsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
        [AppData loadImage:[item objectForKey:@"pic"] view:cell.iconView];
        [cell.nameView setText:[item objectForKey:@"classname"]];
        return cell;
    }
    MatchSaveOptionsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"defaultIdentifier"];
    [cell.nameView setText:[item objectForKey:@"classname"]];
    return cell;
}
- (IBAction)backTouch:(id)sender {
    if (self.onSelected) {
        NSMutableArray *data = [NSMutableArray array];
        NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
        for (NSIndexPath *indexPath in indexPaths) {
            [data addObject:[self.data objectAtIndex:indexPath.row]];
        }
        self.onSelected(self, data);
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end


//搭配发布
@implementation MatchPublishCell
@end
@implementation MatchPublish
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    __weak MatchPublish *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *screen = [AppData userMatchScreen:nil];
        [this setStyle:[screen objectForKey:@"child"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [this getCurrentClass];
            [this reloadData];
        });
    });
}
-(void)getCurrentClass{
    if ([self.data objectForKey:@"client"] == nil) {
        id clientuuid = [self.data objectForKey:@"clientuuid"];
        if (clientuuid) {
            [self.data setValue:[AppData userClientDetail:clientuuid] forKey:@"client"];
        }
    }
    //
    NSMutableDictionary *temp = [self.data objectForKey:@"classs"];
    if (temp == nil) {
        temp = [NSMutableDictionary dictionary];
        //
        NSString *cls = [self.data objectForKey:@"classids"];
        if (isEmpty(cls) == NO) {
            NSArray *classids = [cls componentsSeparatedByString:@","];
            for (id classid in classids) {
                id item = [self findChild:classid];
                if (item) {
                    id pid = [item objectForKey:@"parentid"];
                    NSMutableArray *child = [temp objectForKey:pid];
                    if (child == nil) {
                        child = [NSMutableArray array];
                        [temp setValue:child forKey:pid];
                    }
                    if ([child containsObject:item] == NO) {
                        [child addObject:item];
                    }
                }
            }
        }
    }
    [self setClasss:temp];
}
-(id)findChild:(id)classid{
    for (id style in self.style) {
        if ([style isKindOfClass:NSDictionary.class]) {
            for (id item in [style objectForKey:@"child"]) {
                if ([[item objectForKey:@"id"] intValue] == [classid intValue]) {
                    return item;
                }
            }
        }
    }
    return nil;
}
-(void)reloadData{
    [self.photoView setImage:[self.data objectForKey:@"bitmap"]];
    [self.nameView setText:[AppData objToString:[self.data objectForKey:@"matchname"] lable:nil]];
    [self.infoView setText:[AppData objToString:[self.data objectForKey:@"desc"] lable:nil]];
    //
    for (int i=0; i<self.style.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        MatchPublishCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            id item = [self.style objectAtIndex:i];
            if ([item isKindOfClass:NSDictionary.class]) {
                id key = [item objectForKey:@"id"];
                id classs = [self.classs objectForKey:key];
                if (classs) {
                    NSMutableSet *names = [NSMutableSet set];
                    for (id item in classs) {
                        [names addObject:[item objectForKey:@"classname"]];
                    }
                    if ([names count] > 0) {
                        [cell.nameView setText:[[names allObjects] componentsJoinedByString:@","]];
                    }
                }
            }
        }
    }
}
-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(nullable id)sender{
    if([identifier isEqualToString:@"MatchPublishResult"]){
        if (publishResult == NO) {
            NSMutableSet *ids = [NSMutableSet set];
            for (id items in [self.classs allValues]) {
                for (id item in items) {
                    [ids addObject:[item objectForKey:@"id"]];
                }
            }
            //
            [self.data setValue:self.classs forKey:@"classs"];
            [self.data setValue:self.nameView.text forKey:@"matchname"];
            [self.data setValue:[[ids allObjects] componentsJoinedByString:@","] forKey:@"classids"];
            //
            id temp = [AppData userShareMatch:self.data];
            if (temp) {
                return YES;
            }
            return NO;
        }
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender{
    __weak MatchPublish *this = self;
    if ([segue.destinationViewController isKindOfClass:MatchSaveOptions.class]) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        if (indexPath) {
            id item = [this.style objectAtIndex:indexPath.row];
            MatchSaveOptions *ctrl = segue.destinationViewController;
            [ctrl setClasss:[this.classs objectForKey:[item objectForKey:@"id"]]];
            [ctrl setData:[item objectForKey:@"child"]];
            [ctrl setType:indexPath.row];
            [ctrl setOnSelected:^(id target, id result){
                [this.classs setValue:result forKey:[item objectForKey:@"id"]];
                //
                NSMutableSet *names = [NSMutableSet set];
                for (id item in result) {
                    [names addObject:[item objectForKey:@"classname"]];
                }
                MatchPublishCell *cell = sender;
                [cell.nameView setText:[[names allObjects] componentsJoinedByString:@","]];
                [this.navigationController popViewControllerAnimated:YES];
            }];
        }
        return;
    }
    if ([segue.destinationViewController isKindOfClass:MatchPublishSuccess.class]) {
        MatchPublishSuccess *ctrl = segue.destinationViewController;
        [ctrl setName:[self.data objectForKey:@"matchname"]];
    }
}
-(IBAction)closeTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
-(IBAction)saveTouch:(id)sender {
    if ([self.nameView.text length] == 0) {
        [UIAlertController show:nil message:@"搭配名称不能为空!" buttons:nil handler:nil];
        return;
    }
    if ([self.spaceView.text length] == 0) {
        [UIAlertController show:nil message:@"空间属性不能为空!" buttons:nil handler:nil];
        return;
    }
    if ([self.styleView.text length] == 0) {
        [UIAlertController show:nil message:@"风格属性不能为空!" buttons:nil handler:nil];
        return;
    }
    if ([self.colorView.text length] == 0) {
        [UIAlertController show:nil message:@"颜色属性不能为空!" buttons:nil handler:nil];
        return;
    }
    if (self.onSelected) {
        NSMutableSet *ids = [NSMutableSet set];
        for (id items in [self.classs allValues]) {
            for (id item in items) {
                [ids addObject:[item objectForKey:@"id"]];
            }
        }
        //
        id client = [self.data objectForKey:@"client"];
        [self.data setValue:[client objectForKey:@"id"] forKey:@"clientid"];
        [self.data setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
        //
        [self.data setValue:self.classs forKey:@"classs"];
        [self.data setValue:self.infoView.text forKey:@"desc"];
        [self.data setValue:self.nameView.text forKey:@"matchname"];
        [self.data setValue:[[ids allObjects] componentsJoinedByString:@","] forKey:@"classids"];
        self.onSelected(self, self.data);
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
-(NSMutableDictionary *)classs{
    if (_classs == nil) {
        [self setClasss:[NSMutableDictionary dictionary]];
    }
    return _classs;
}
@end

//搭配保存
@implementation MatchSaveCell
@end
@implementation MatchSave
- (void)viewDidLoad{
    [super viewDidLoad];
    //
    __weak MatchSave *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *screen = [AppData userMatchScreen:nil];
        [this setStyle:[screen objectForKey:@"child"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [this getCurrentClass];
            [this reloadData];
        });
    });
}
-(void)getCurrentClass{
    if ([self.data objectForKey:@"client"] == nil) {
        id clientuuid = [self.data objectForKey:@"clientuuid"];
        if (clientuuid) {
            [self.data setValue:[AppData userClientDetail:clientuuid] forKey:@"client"];
        }
    }
    //
    NSMutableDictionary *temp = [self.data objectForKey:@"classs"];
    if (temp == nil) {
        temp = [NSMutableDictionary dictionary];
        //
        NSString *cls = [self.data objectForKey:@"classids"];
        if (isEmpty(cls) == NO) {
            NSArray *classids = [cls componentsSeparatedByString:@","];
            for (id classid in classids) {
                id item = [self findChild:classid];
                if (item) {
                    id pid = [item objectForKey:@"parentid"];
                    NSMutableArray *child = [temp objectForKey:pid];
                    if (child == nil) {
                        child = [NSMutableArray array];
                        [temp setValue:child forKey:pid];
                    }
                    if ([child containsObject:item] == NO) {
                        [child addObject:item];
                    }
                }
            }
        }
    }
    [self setClasss:temp];
}
-(id)findChild:(id)classid{
    for (id style in self.style) {
        if ([style isKindOfClass:NSDictionary.class]) {
            for (id item in [style objectForKey:@"child"]) {
                if ([[item objectForKey:@"id"] intValue] == [classid intValue]) {
                    return item;
                }
            }
        }
    }
    return nil;
}
-(void)reloadData{
    [self.nameView setText:[AppData objToString:[self.data objectForKey:@"matchname"] lable:nil]];
    [self.infoView setText:[AppData objToString:[self.data objectForKey:@"desc"] lable:nil]];
    //
    id client = [self.data objectForKey:@"client"];
    if (client == nil) {
        client = [TMGlobal valueForKey:@"client"];
        [self.data setValue:client forKey:@"client"];
    }
    if (client) {
        [self.clientView setText:[AppData objToString:[client objectForKey:@"truename"] lable:nil]];
    }
    //
    for (int i=0; i<self.style.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
        MatchSaveCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            id tmp = [self.style objectAtIndex:i];
            if ([tmp isKindOfClass:NSDictionary.class]) {
                id key = [tmp objectForKey:@"id"];
                id classs = [self.classs objectForKey:key];
                if (classs) {
                    NSMutableSet *names = [NSMutableSet set];
                    for (id item in classs) {
                        [names addObject:[item objectForKey:@"classname"]];
                    }
                    if ([names count]>0) {
                        [cell.nameView setText:[[names allObjects] componentsJoinedByString:@","]];
                    }
                }
                [cell.labelView setText:[tmp objectForKey:@"name"]];
            }
        }
    }
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __weak MatchSave *this = self;
    if ([segue.destinationViewController isKindOfClass:MatchSaveOptions.class]) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        if (indexPath) {
            id item = [this.style objectAtIndex:indexPath.row];
            if ([item isKindOfClass:NSDictionary.class] == NO) {
                item = nil;
            }
            //
            MatchSaveOptions *ctrl = segue.destinationViewController;
            [ctrl setClasss:[self.classs objectForKey:[item objectForKey:@"id"]]];
            [ctrl setData:[item objectForKey:@"child"]];
            [ctrl setType:indexPath.row];
            [ctrl setOnSelected:^(id target, id result){
                [this.classs setValue:result forKey:[item objectForKey:@"id"]];
                //
                NSMutableSet *names = [NSMutableSet set];
                for (id item in result) {
                    [names addObject:[item objectForKey:@"classname"]];
                }
                if ([names count]>0) {
                    MatchSaveCell *cell = sender;
                    [cell.nameView setText:[[names allObjects] componentsJoinedByString:@","]];
                }
                [this.navigationController popViewControllerAnimated:YES];
            }];
        }
    }
    if ([segue.destinationViewController isKindOfClass:UserCenterPick.class]) {
        UserCenterPick *ctrl = segue.destinationViewController;
        [ctrl setClient:[self.data objectForKey:@"client"]];
        [ctrl setOnSelected:^(id target, id result){
            [this.data setValue:result forKey:@"current"];
            //
            MatchSaveCell *cell = sender;
            [cell.nameView setText:[result objectForKey:@"truename"]];
            [this.navigationController popToRootViewControllerAnimated:YES];
        }];
    }
}
//
-(IBAction)closeTouch:(id)sender {
    if (self.onSelected) {
        self.onSelected(self, nil);
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
-(IBAction)saveTouch:(id)sender {
    if ([self.nameView.text length] == 0) {
        [UIAlertController show:nil message:@"搭配名称不能为空!" buttons:nil handler:nil];
        return;
    }
    if ([self.spaceView.text length] == 0) {
        [UIAlertController show:nil message:@"空间属性不能为空!" buttons:nil handler:nil];
        return;
    }
    if ([self.styleView.text length] == 0) {
        [UIAlertController show:nil message:@"风格属性不能为空!" buttons:nil handler:nil];
        return;
    }
    if ([self.colorView.text length] == 0) {
        [UIAlertController show:nil message:@"颜色属性不能为空!" buttons:nil handler:nil];
        return;
    }
    if (self.onSelected) {
        NSMutableSet *ids = [NSMutableSet set];
        for (id items in [self.classs allValues]) {
            for (id item in items) {
                [ids addObject:[item objectForKey:@"id"]];
            }
        }
        //
        id client = [self.data objectForKey:@"current"];
        if (client == nil) {
            client = [self.data objectForKey:@"client"];
        }else{
            [self.data setValue:client forKey:@"client"];
        }
        [self.data setValue:[client objectForKey:@"id"] forKey:@"clientid"];
        [self.data setValue:[client objectForKey:@"uuid"] forKey:@"clientuuid"];
        //
        [self.data setValue:self.classs forKey:@"classs"];
        [self.data setValue:self.infoView.text forKey:@"desc"];
        [self.data setValue:self.nameView.text forKey:@"matchname"];
        [self.data setValue:[[ids allObjects] componentsJoinedByString:@","] forKey:@"classids"];
        self.onSelected(self, self.data);
    }else{
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}
-(NSMutableDictionary *)classs{
    if (_classs == nil) {
        [self setClasss:[NSMutableDictionary dictionary]];
    }
    return _classs;
}
@end
